<template>
  <el-container>
    <el-header style="height: 80px;">HS资产管理系统</el-header>
    <!-- 主要窗口 -->
    <el-main>
      <!-- 面包屑导航 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>首页</el-breadcrumb-item>
        <el-breadcrumb-item>资产管理</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 表单 -->
      <el-form :inline="true" style="margin-top: 20px;">
        <!-- 不加此行，无法显示 查询Form表单,20px是上下距离-->
        <el-row>
          <el-col :span="8">
            <el-form-item label="查询">
              <el-input v-model="inputStr" placeholder="输入条件查询" style="width: 420px;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="text-align: right;padding-right:10px;">
            <el-button-group>
              <el-button type="primary" icon="el-icon-search" @click="queryStudents()">查询</el-button>
              <el-button type="primary" icon="el-icon-tickets" @click="getStudents()">显示全部</el-button>
              <el-button
                type="primary"
                icon="el-icon-circle-plus-outline"
                @click="addStudent()"
                close-on-click-modal="false"
              >添加</el-button>
            </el-button-group>
          </el-col>
          <el-col :span="2">
            <el-upload :show-file-list="false" :http-request="uploadExcelPost">
              <el-button type="primary">导入Excel</el-button>
            </el-upload>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click="exportToExcel()">导出Excel</el-button>
          </el-col>
        </el-row>
      </el-form>
      <!-- 表格 -->
      <el-table :data="pageStudents" border style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" >
          <!-- 此步是添加复选框 -->
        </el-table-column>
        <el-table-column prop="id" label="序号" width="60"></el-table-column>
        <el-table-column prop="sno" label="商品名称" width="150"></el-table-column>
        <el-table-column prop="sname" label="数量" width="100"></el-table-column>
        <el-table-column prop="gender" label="购买价格" width="90"></el-table-column>
        <el-table-column prop="birthday" label="购买日期" width="120"></el-table-column>
        <el-table-column prop="mobile" label="购买厂家" width="150"></el-table-column>
        <el-table-column prop="email" label="保管人" width="280"></el-table-column>
        <el-table-column prop="address" label="产品备注" width="630"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="success" icon="el-icon-more" circle @click="viewStudent(scope.row)"></el-button>
            <el-button type="primary" icon="el-icon-edit" circle @click="updateStudent(scope.row)"></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              @click="submitDeleteStudent(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-row style="margin-top: 20px;">
        <el-col :span="8" style="text-align: left">
          <el-button
            type="danger"
            icon="el-icon-search"
            size="mini"
            @click="submitDeleteStudents()"
          >批量删除</el-button>
        </el-col>
        <el-col :span="12" style="text-align: right">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentpage"
            :page-sizes="[5, 10, 50, 100]"
            :page-size="pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </el-col>
      </el-row>

      <!-- 弹出框的学生明细表 -->
      <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="50%"
        :close-on-click-modal="false"
        @close="closeDialogForm('studentForm')"
      >
        <el-form
          :inline="true"
          :model="studentForm"
          :rules="rules"
          ref="studentForm"
          style="margin-left: 20px;"
          label-width="110px"
          label-position="right"
          size="mini"
        >
          <!-- 添加学生照片 -->
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :http-request="uploadPicturePost"
            :disabled="isView"
            style="text-align: center;margin:20px;"
          >
            <img v-if="studentForm.image" :src="studentForm.imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>

          <el-form-item label="商品名称:">
            <el-input v-model="studentForm.sno" suffix-icon="el-icon-edit" :disabled="isView"></el-input>
          </el-form-item>
          <el-form-item label="数量:">
            <el-input v-model="studentForm.sname" suffix-icon="el-icon-edit" :disabled="isView"></el-input>
          </el-form-item>
          <el-form-item label="购买价格:">
            <el-input v-model="studentForm.gender" suffix-icon="el-icon-edit" :disabled="isView"></el-input>
          </el-form-item>
          <el-form-item label="购买日期:">
            <el-date-picker
              type="date"
              v-model="studentForm.birthday"
              placeholder="选择日期"
              size="mini"
              style="width:95%"
              :disabled="isView"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="购买厂家:">
            <el-input v-model="studentForm.mobile" suffix-icon="el-icon-edit" :disabled="isView"></el-input>
          </el-form-item>
          <el-form-item label="保管人:">
            <el-input v-model="studentForm.email" suffix-icon="el-icon-edit" :disabled="isView"></el-input>
          </el-form-item>
          <el-form-item label="产品备注:">
            <el-input
              v-model="studentForm.address"
              style="width:253%"
              suffix-icon="el-icon-edit"
              :disabled="isView"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button vmode="true" @click="submitStudentForm('studentForm')" v-show="!isView">确 定</el-button>
          <el-button @click="closeDialogForm('studentForm')">取 消</el-button>
        </span>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      baseURL: "http://192.168.1.177:8000/",
      students: [
        {
          id: 12,
          sno: "插排",
          sname: 12,
          gender: 8,
          birthday: "2020-09-14",
          mobile: "郭氏插排",
          email: "郭帅",
          address: "此产品为全球最先进的智能插排",
        },
      ],
      //复选框
      testfxk: [],
      total: 0,
      currentpage: 1,
      pageStudents: [],
      pagesize: 5,
      inputStr: "",
      //===弹出框表单====
      dialogVisible: false,
      //===每个学生的详细信息
      studentForm: {
        sno: "",
        sname: "",
        gender: "",
        birthday: "",
        mobile: "",
        email: "",
        address: "",
        image: "",
        imageUrl: "",
      },
      //弹出框标题
      dialogTitle: "",
      //弹出框内容是否置灰色和确定按钮是否隐藏
      isEdit: false,
      isView: false,

      rules: {
        sno: [
          { required: true, message: "学号不能为空", trigger: "blur" },
          {
            pattern: /^[9][5]\d{3}$/,
            message: "学号必须是95开头的五位数",
            trigger: "blur",
          },
        ],

        name: [
          { required: true, message: "姓名不能为空", trigger: "blur" },
          {
            pattern: /^[\u4e00-\u9fa5]{2,5}$/,
            message: "姓名必须是2-5个汉字",
            trigger: "blur",
          },
        ],
      },
    };
  },

  created() {
    console.log("12222222222222");
    this.getStudents();
  },

  methods: {
    getStudents: function () {
      //this  save
      let that = this;
      axios
        .get(that.baseURL+ "students/")
        .then(function (res) {
          //请求成功后执行的函数
          if (res.data.code === 1) {
            that.students = res.data.data;
            that.total = res.data.data.length;
            //获取当前页的数据
            console.log("是否来温热官方");
            that.getPageStudents();
            console.log("是否来了");
            that.$message({
              showClose: true,
              message: "数据加载成功！",
              type: "success",
            });
            // console.log(that.students);
          } else {
            that.$message({
              showClose: true,
              message: "很遗憾，登录失败！" + res.data.msg,
              type: "error",
            });
          }
        })
        .catch(function (err) {
          //请求失败后执行的函数
          console.log(err);
        });
    },

    //实现学生信息查询
    queryStudents: function () {
      console.log("实现学生信息查询");
      let that = this;
      axios
        .post(that.baseURL+"students/query/", { inputstr: that.inputStr })
        .then(function (res) {
          if (res.data.code === 1) {
            that.students = res.data.data;
            that.total = res.data.data.length;
            that.getPageStudents();
          } else {
            that.$message.error("获取后端结果出现异常~~~");
          }
        })
        .catch(function () {
          console.log("获取后端查询结果出现异常！");
        });
    },
    //获取当前页的学生数据
    getPageStudents() {
      //清空pageStudents中的数据
      this.pageStudents = [];
      //获得当前页的数据
      for (
        let i = (this.currentpage - 1) * this.pagesize;
        i < this.total;
        i++
      ) {
        //遍历数据添加到pageStudent中
        this.pageStudents.push(this.students[i]);
        //判断是否达到一页的要求
        if (this.pageStudents.length === this.pagesize) break;
      }
    },

    handleOpen(key, keyPath) {
      console.log(key, keyPath);
    },

    //显示全部学生信息
    getAllStudent() {
      this.inputStr = "";
      this.getStudents();
    },

    //添加学生
    addStudent() {
      this.dialogVisible = true;
      this.dialogTitle = "添加学生信息";
    },

    //根据Id获取image
    getImageBySno(sno) {
        console.log("郭帅领")
        console.log(sno)
        console.log(this.students)
      //遍历
      let oneStudent      //此处在网上查的，需要加这个let 否则报错
      for (oneStudent of this.students) {
        //判断
        if (oneStudent.sno == sno) {
          return oneStudent.image;
        }
      }
    },

    //查看学生明细
    viewStudent(row) {
      this.isView = true;
      this.dialogTitle = "查看资产信息";
      this.dialogVisible = true;
      // this.studentForm=row;
      //深拷贝
      this.studentForm = JSON.parse(JSON.stringify(row));
      //获取照片
      this.studentForm.image = this.getImageBySno(row.sno);
      console.log("郭帅帅")
      console.log(this.studentForm.image)
      //获取照片URL
      this.studentForm.imageUrl =
        this.baseURL + "media/" + this.studentForm.image;
    },
    //修改学生信息
    updateStudent(row) {
      this.isEdit = true;
      this.dialogTitle = "修改资产信息";
      this.dialogVisible = true;
      //浅copy
      // this.studentForm=row;
      //①深copy
      // this.studentForm.sno=row.sno;
      // this.studentForm.sname=row.name;
      //②深copy
      this.studentForm = JSON.parse(JSON.stringify(row));
      //获取照片
      this.studentForm.image = this.getImageBySno(row.sno);
      //获取照片URL
      this.studentForm.imageUrl =
        this.baseURL + "media/" + this.studentForm.image;
    },

    //关闭和清空dialog
    closeDialogForm(formName) {
      //重置表单的校验（不填，直接提交信息、再次打开弹出框会保留，）
      this.$refs[formName].resetFields();
      //清空
      this.studentForm.sno = "";
      this.studentForm.sname = "";
      this.studentForm.gender = "";
      this.studentForm.birthday = "";
      this.studentForm.mobile = "";
      this.studentForm.email = "";
      this.studentForm.address = "";
      this.studentForm.image = "";
      this.studentForm.imageUrl = "";
      //关闭
      this.dialogVisible = false;

      //
      this.isEdit = false;
      this.isView = false;
    },

    //提交学生的表单（增加、修改）
    submitStudentForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //校验成功后
          if (this.isEdit) {
            //修改
            this.submitUpdateStudnt();
          } else {
            //添加
            this.submitAddStudnt();
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    //添学生信息到数据库的函数
    submitAddStudnt() {
      let that = this;
      axios
        .post(that.baseURL + "student/add/", that.studentForm)
        .then((res) => {
          if (res.data.code === 1) {
            //获取所有学生信息
            that.students = res.data.data;
            //
            that.total = res.data.data.length;
            //
            that.getPageStudents();
            //提示
            that.$message({
              showClose: true,
              message: "添加数据成功",
              type: "success",
            });
            //添加成功，最后关闭弹出框
            this.closeDialogForm("studentForm");
          } else {
            that.$message.error(res.data.msg);
          }
        })
        .catch((err) => {
          console.log(err);
          that.$message.error("获取后端查询结果异常");
        });
    },

    //修改、编辑学生信息到数据库的函数
    submitUpdateStudnt() {
      let that = this;
      axios
        .post(that.baseURL + "student/update/", that.studentForm)
        .then((res) => {
          if (res.data.code === 1) {
            that.students = res.data.data;
            //
            that.total = res.data.data.length;
            //
            that.getPageStudents();
            that.$message({
              showClose: true,
              message: "修改数据成功",
              type: "success",
            });
            //关闭窗体
            this.closeDialogForm("studentForm");
          } else {
            that.$message.error(res.data.msg);
          }
        })
        .catch((err) => {
          //执行失败
          console.log(err);
          that.$message.error("修改时获取后端结果出现异常");
        });
    },

    //删除学生信息(一条)
    submitDeleteStudent(row) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let that = this;
          axios
            .post(that.baseURL + "student/delete/", { sno: row.sno })
            // console.log(row)
            .then((res) => {
              if (res.data.code === 1) {
                //获取所有学生信息
                that.students = res.data.data;
                //获取记录数
                that.total = res.data.data.length;
                //分页
                that.getPageStudents();
                //提示
                that.$message({ message: "删除数据成功！", type: "success" });
              } else {
                that.$message.error(res.data.msg);
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //批量删除学生记录
    submitDeleteStudents() {
      this.$confirm("此操作将永久批量删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let that = this;
          axios
            .post(that.baseURL + "students/delete/", { studentt: that.testfxk })
            .then((res) => {
              if (res.data.code === 1) {
                //获取所有学生信息
                that.students = res.data.data;
                //获取总共条数，并赋值，此处起到刷新界面的作用
                that.total = res.data.data.length;
                //重新获取页面的所有数据，此处起到刷新界面的作用
                that.getPageStudents();
                //提示
                that.$message({
                  message: "批量删除数据成功！",
                  type: "success",
                });
              } else {
                that.$message.error(res.data.msg);
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //多选框，选择批量删除时执行到此步骤
    handleSelectionChange(val) {
      this.testfxk = val;
      console.log(val);
    },

    //选择学生头像后点击确定后触发的事件
    uploadPicturePost(file) {
      //定义that
      let that = this;
      //定义一个FormData类
      let fileReq = new FormData();
      //把照片穿进去
      console.log(file);
      console.log("******88888");
      console.log(file.file);
      fileReq.append("avatar", file.file);
      //使用Axios发起Ajax请求
      axios({
        method: "post",
        url: that.baseURL + "upload/",
        data: fileReq,
      })
        .then((res) => {
          // 根据code判断是否成功
          if (res.data.code === 1) {
            //把照片给image
            that.studentForm.image = res.data.name;
            console.log(that.studentForm.image)
            //拼接imageurl
            that.studentForm.imageUrl = that.baseURL + "media/" + res.data.name;
            console.log(that.studentForm.imageUrl)
            // console.log(res.data)
          } else {
            //失败的提示！
            that.$message.error(res.data.msg);
          }
        })
        .catch((err) => {
          console.log(err);
          that.$message.error("上传头像出现异常！");
        });
    },

    //上传excel到后台
    uploadExcelPost(file) {
      let that = this;
      console.log("郭帅");
      console.log(file);
      //定义一个FormData类
      let fileReq = new FormData();
      //把照片穿进去
      fileReq.append("excel", file.file);
      //使用Axios发起Ajax请求
      axios({
        method: "post",
        url: that.baseURL + "excel/import/",
        data: fileReq,
      })
        .then((res) => {
          // 根据code判断是否成功
          if (res.data.code === 1) {
            //把照片给image
            that.students = res.data.data;
            //
            that.total = res.data.data.length;
            that.getPageStudents();

            //弹出框体显示结果
            this.$alert(
              "本次导入完成! 成功：" +
                res.data.success +
                "失败：" +
                res.data.error,
              "导入结果展示",
              {
                confirmButtonText: "确定",
                callback: () => {
                  this.$message({
                    type: "info",
                    message:
                      "本次导入失败数量为：" +
                      res.data.error +
                      ",具体的学号：" +
                      res.data.errors,
                  });
                },
              }
            );
            //把失败明细打印
            console.log(
              "本次导入失败数量为：" + res.data.error + ",具体的学号："
            );
            console.log(res.data.errors);
          } else {
            //失败的提示！
            that.$message.error(res.data.msg);
          }
        })
        .catch((err) => {
          console.log(err);
          that.$message.error("上传Excel出现异常！");
        });
    },

    //导出excel
    exportToExcel() {
      let that = this;
      axios
        .get(that.baseURL + "excel/export/")
        .then((res) => {
          if (res.data.code === 1) {
            //拼接excel 的完整URL
            let url = that.baseURL + "media/" + res.data.name;
            //下载
            window.open(url);
          } else {
            that.$message.error("导出Excel出现异常！");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //分页时修改每页的行数
      handleSizeChange(size) {
      console.log("分页时修改每页的行数------是否来过");
      //修改当前每页数据行数
      this.pagesize = size;
      //数据重新分页
      this.getPageStudents();
    },
    //调整当前的页码
    handleCurrentChange(pageNumber) {
      //修改当前的页码
      this.currentpage = pageNumber;
      //数据重新分页
      this.getPageStudents();
    },

  },
};
</script>


<style scoped>
.el-dialog .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

}
.el-dialog .avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.el-dialog  .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.el-dialog .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>